Dependent Queries
依赖(或串行)查询在执行之前依赖于之前的查询完成。要实现这一点,只需使用enabled选项来告诉查询何时准备运行即可:
// Get the user
const { data: user } = useQuery({
queryKey: ['user', email],
queryFn: getUserByEmail,
})
const userId = user?.id
// Then get the user's projects
const {
status,
fetchStatus,
data: projects,
} = useQuery({
queryKey: ['projects', userId],
queryFn: getProjectsByUser,
// The query will not execute until the userId exists
enabled: !!userId,
})
The projects
query will start in:
status: "loading"
fetchStatus: 'idle'
一旦user
获取到,projects
query 将被启用并且转变为
status: "loading"
fetchStatus: 'fetching'
查询成功之后,将变成:
status: "success"
fetchStatus: 'idle'